package com.ltxtiyu.video.interceptor;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ltxtiyu.video.common.JsonTool;
import com.ltxtiyu.video.common.RetEnum;
import com.ltxtiyu.video.common.SecurityConstant;
import com.ltxtiyu.video.entity.TokenStore;
import com.ltxtiyu.video.entity.User;
import com.ltxtiyu.video.service.app.TokenStoreService;
import com.ltxtiyu.video.service.app.UserService;
import com.ltxtiyu.video.tool.ObjectTool;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class SecurityInterceptor implements HandlerInterceptor {

    @Reference
    private UserService userService;
    @Reference
    private TokenStoreService tokenStoreService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String channel = request.getParameter("channel");
        if (SecurityConstant.CHANNEL_ANDROID.equals(channel) || SecurityConstant.CHANNEL_IOS.equals(channel)) {
            String oauthToken = request.getParameter("oauthToken");

            // 校验App的token
            TokenStore tokenStore = tokenStoreService.selectByOauthToken(oauthToken, SecurityConstant.TOKEN_TYPE_APP);
            // token记录不存在
            if (tokenStore == null) {
                writeRes(response, RetEnum.TOKEN_ERROR);
                return false;
            }
            // token超时
            if ((tokenStore.getCreateTime().getTime() + 7200000) < System.currentTimeMillis()) {
                writeRes(response, RetEnum.TOKEN_EXPIRE);
                return false;
            }

            User user = userService.selectByPrimaryKey(tokenStore.getUserId());
            if(user == null || user.getId() == null){   // 用户不存在
                writeRes(response,RetEnum.OAUTH_CHECK_INEXISTENCE);
            }
            if(null != user && user.getStatus().intValue() != 1){   // 用户被封停
                writeRes(response, RetEnum.OAUTH_CHECK_BANNED);
                return false;
            }

            request.setAttribute("userId", String.valueOf(tokenStore.getUserId()));
            request.setAttribute("user", user);
        } else if (SecurityConstant.CHANNEL_M_SITE.equals(channel)) {
            String oauthToken = request.getParameter("oauthToken");
            Integer moveMark = ObjectTool.numberNullConvert(request.getParameter("moveMark"), -1);
            TokenStore tokenStore = null;
            if(moveMark==0){
                // 校验M站的token
                tokenStore = tokenStoreService.selectByOauthToken(oauthToken, SecurityConstant.TOKEN_TYPE_APP);
            }else if(moveMark==1){
                tokenStore = tokenStoreService.selectByOauthToken(oauthToken, SecurityConstant.TOKEN_TYPE_M_SITE);
            }

            // token记录不存在
            if (tokenStore == null) {
                writeRes(response, RetEnum.TOKEN_ERROR);
                return false;
            }
            // token超时
            if ((tokenStore.getCreateTime().getTime() + 7200000) < System.currentTimeMillis()) {
                writeRes(response, RetEnum.TOKEN_EXPIRE);
                return false;
            }

            User user = userService.selectByPrimaryKey(tokenStore.getUserId());
            if(user == null || user.getId() == null){   // 用户不存在
                writeRes(response,RetEnum.OAUTH_CHECK_INEXISTENCE);
            }
            if(null != user && user.getStatus().intValue() != 1){
                writeRes(response, RetEnum.OAUTH_CHECK_BANNED);
                return false;
            }

            request.setAttribute("userId", String.valueOf(tokenStore.getUserId()));
            request.setAttribute("user", user);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }

    private void writeRes(HttpServletResponse response, RetEnum re)
            throws Exception {
        String json = JsonTool.genJson(re);
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }

}
